#include <myheader.h>

/*Usage:使用select进行通信 */
int main(int argc, char *argv[])
{
    //打开管道
    int w_pipe_fd = open("1.pipe",O_WRONLY);
    int r_pipe_fd = open("2.pipe",O_RDONLY);
    
    //将两个文件描述符放入select监听集合
    //建立set
    fd_set listen_set;

    while(1){
    FD_ZERO(&listen_set);
    FD_SET(STDIN_FILENO,&listen_set);
    FD_SET(r_pipe_fd,&listen_set);

    int res_select = select(r_pipe_fd+1, &listen_set,
                            NULL,NULL, NULL);
    if(FD_ISSET(STDIN_FILENO,&listen_set)){
        //说明要进行写操作，从stdin当中读入数据
        char buf[60] = {0};
        int read_cnt = read(STDIN_FILENO,buf,sizeof(buf));
        //将数据通过2.pipe发送
        write(w_pipe_fd,buf,read_cnt);
        if((read_cnt == 2) && buf[0] == '1'){
            printf("end!\n");
            exit(1);
        }
    }else if(FD_ISSET(r_pipe_fd,&listen_set)){
        char buf[60] = {0};
        //说明要进行读操作，从pipe中读取数据
        int read_pipe_cnt = read(r_pipe_fd,buf,sizeof(buf));
        //看看传过来的数是否是1
        if((read_pipe_cnt == 2) && (buf[0] == '1')){
            printf("end!\n");
            exit(1);
        }
        printf("%s\n",buf);
    }
    }
    close(r_pipe_fd);
    close(w_pipe_fd);
    return 0;
}

